package com.vtech.ws.cxf.service.impl;

import com.vtech.ws.commons.FileEntity;
import com.vtech.ws.cxf.config.FilePathConfig;
import com.vtech.ws.cxf.service.SoapFileService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.jws.WebService;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * TODO
 *
 * @author houzhiwei
 * @date 2018/9/6 23:05
 */
@Service
@WebService(targetNamespace = "http://service.cxf.ws.vtech.com",serviceName = "SoapFileService")
public class SoapFileServiceImpl implements SoapFileService {

    @Autowired
    private FilePathConfig pathConfig;

    @Override
    public String upload(FileEntity upload) {
        DataHandler handler = upload.getFile();
        try {
            InputStream is = handler.getInputStream();

            String extension = upload.getExtension();
            File file2Save;
            if (StringUtils.isNotBlank(extension)) {
                file2Save = new File(pathConfig.getUploadPath() + File.separator + upload.getName() + "." + extension);
            } else {
                file2Save = new File(pathConfig.getUploadPath() + File.separator + upload.getName());
            }
            Files.copy(is, file2Save.toPath(), StandardCopyOption.REPLACE_EXISTING);
            is.close();
//            FileUtils.copyInputStreamToFile(is, file2Save);
        } catch (IOException e) {
            e.printStackTrace();
            return "FAILED";
        }
        return "SUCCESS";
    }

    @Override
    public FileEntity download() {
        String outputPath = pathConfig.getOutputPath();
        String filename = outputPath + File.separator + "01_DEM.tif";
        FileEntity download = setFileEntity(filename);
        return download;
    }


    private FileEntity setFileEntity(String filename) {
        // 需要下载的文件
        File file = new File(filename);
        FileEntity fileEntity = new FileEntity();
        fileEntity.setSize(file.length());
        // 扩展名
        fileEntity.setExtension(FilenameUtils.getExtension(filename));
        // 文件名(不包括扩展名)
        fileEntity.setName(FilenameUtils.getBaseName(filename));
        // 数据源
        DataSource source = new FileDataSource(file);
        fileEntity.setFile(new DataHandler(source));

        return fileEntity;
    }
}
